<template>
	<div class="page-wrapper fxyj-wrapper">
		<!-- 风险预警 -->
		<!-- 导航栏 -->
		<navbar />
		<Map :config="MapConfig" @getMap="getMap" />
		<MapTool :map-tool="MapToolConfig" @getKey="getKey">
			<template
				v-for="item in mapToolsRows"
				v-slot:[item.key]
				:mapToolsRows="mapToolsRows"
			>
				<div
					:key="item.key"
					@click="clickHandler(item.key, item.active)"
					v-html="item.render"
				/>
			</template>
		</MapTool>
		<mapTable
			:c-option="cOption"
			:popup-type="popupType"
			@refresh-map="refreshMap"
		></mapTable>

		<!-- <div class="absolute bottom-0 left-0 z-1 invisible sm:visible">
      <Legend :default-option="legendConfig.defaultOption" :config="legendConfig.config" />
    </div> -->

		<!-- 侧边导航栏 -->
		<sidebar class="sidebar-container" />
		<!-- 日期范围 -->
		<time-period
			:start-time="product.startTime"
			:date="product.date"
			:moment="product.moment"
		></time-period>
		<!-- 右边面板 -->
		<product
			:modes-select="modesSelect"
			:hours-select="hoursSelect"
			@get-forecast="getForecast"
			@change-period="getForecast"
			@site-search="searchSite"
			@make-product="makeProduct"
		/>
		<!-- 制作产品 -->
		<el-dialog
			center
			width="40%"
			title="产品制作"
			:visible="dialogVisible"
			:close-on-click-modal="false"
			:before-close="handleClose"
		>
			<el-form
				ref="productForm"
				label-width="6em"
				label-suffix=":"
				:model="product"
				:rules="productRules"
			>
				<el-form-item label="预报人员" prop="forecastUsr">
					<el-autocomplete
						placeholder="请输入预报人员"
						class="inline-input"
						value-key="label"
						v-model="product.forecastUsr"
						:fetch-suggestions="
							(queryString, cb) => {
								makerFilter(queryString, cb, 'fUsers');
							}
						"
					>
						<template slot-scope="{ item }">
							<div class="maker-label">{{ item.label }}</div>
						</template>
					</el-autocomplete>
					<!-- <el-select v-model="product.forecastUsr">
            <el-option
              v-for="(fu, index) in maker.fUsers"
              :key="fu.value"
              :label="fu.label"
              :value="fu.label"
            ></el-option>
          </el-select> -->
				</el-form-item>
				<el-form-item label="录入人员" prop="enteringUsr">
					<el-autocomplete
						placeholder="请输入录入人员"
						class="inline-input"
						value-key="label"
						v-model="product.enteringUsr"
						:fetch-suggestions="
							(queryString, cb) => {
								makerFilter(queryString, cb, 'eUsers');
							}
						"
					>
						<template slot-scope="{ item }">
							<div class="maker-label">{{ item.label }}</div>
						</template>
					</el-autocomplete>
					<!-- <el-select v-model="product.enteringUsr">
            <el-option
              v-for="(uu, index) in maker.eUsers"
              :key="uu.value"
              :label="uu.label"
              :value="uu.label"
            ></el-option>
          </el-select> -->
				</el-form-item>
				<el-form-item label="校验人员" prop="verifyUsr">
					<el-autocomplete
						placeholder="请输入校验人员"
						class="inline-input"
						value-key="label"
						v-model="product.verifyUsr"
						:fetch-suggestions="
							(queryString, cb) => {
								makerFilter(queryString, cb, 'vUsers');
							}
						"
					>
						<template slot-scope="{ item }">
							<div class="maker-label">{{ item.label }}</div>
						</template>
					</el-autocomplete>
					<!-- <el-select v-model="product.verifyUsr">
            <el-option
              v-for="(vu, index) in maker.vUsers"
              :key="vu.value"
              :label="vu.label"
              :value="vu.label"
            ></el-option>
          </el-select> -->
				</el-form-item>
				<el-form-item label="签发单位" prop="department">
					<el-input v-model="product.department"></el-input>
				</el-form-item>
				<el-form-item style="text-align: center">
					<el-button type="primary" @click="submitProduct"
						>生成产品</el-button
					>
				</el-form-item>
			</el-form>
		</el-dialog>
	</div>
</template>

<script>
import Navbar from '@/components/Navbar'
import Sidebar from '@/components/Sidebar'
import Product from '@/components/Product'
import TimePeriod from '@/components/TimePeriod'

import { hours_f, proRules } from '@/utils/constant.js'
import { getAction, postAction } from '@/api/action'

import {
	module,
	legendConfig,
	MapToolConfig
} from '../fxyj/config'
import {
	MapConfig,
	ChartConfig,
	PopLayerConfig,
	BaseMapConfig
} from '../map.config'

import cnBorder from '../../assets/geoData/450400.json'
import {
	isInChina
} from '../../utils/mapUtils/isInChina'
import {
	requestPointData,
	formateData,
	renderChart
} from '../../utils/mapUtils/renderChart'
import 'ol/ol.css'
import 'weatherstar-switch/dist/switch.css'
import dayjs from 'dayjs'
import Map from '@automan-component/map'
import Legend from '@automan-component/legend'
import MapTool from '../../components/Map/mapTool'

import mapTable from '../../components/Map/mapTable'

import CuiteMap from '../../utils/map'
import {
	clear,
	measure,
	print
} from '@automan-component/maputils'

import cuiteFilter from '../../utils/mapUtils/filter'


export default {
	name: 'Fxyj',
	components: {
		Navbar,
		Sidebar,
		Product,
		TimePeriod,
		Map,
		MapTool,
		mapTable,
		Legend
	},
	data() {
		return {
			urls: {
				getRiskWarning: '/api/riskWarning/getRiskWarning',
				makeProduce: '/api/riskWarning/makeProduce',
				maker: '/api/makeUser/list', // 产品制作人数据查询
			},
			modesSelect: [{
				label: '客观预报',
				value: '1',
			},],
			hoursSelect: hours_f,
			dialogVisible: false,
			pageLoading: null,
			product: {
				pattern: '1', // 模式
				startTime: '08', // 起报
				date: dayjs().format('YYYY-MM-DD'),
				moment: '12', // 时效
				forecastUsr: '',
				enteringUsr: '',
				verifyUsr: '',
				department: '梧州市气象局',
			},
			productRules: proRules,
			maker: {
				fUsers: [],
				eUsers: [],
				vUsers: [],
			},
			MapConfig,
			MapToolConfig,
			legendConfig,
			date: dayjs().format('YYYY-MM-DD'),
			map: null,
			cuitemap: null,
			cuitefilter: null,
			mapToolsRows: [],
			layerGroup: [],
			mapdata: null,
			loading: false,
			chartOption: ChartConfig.options,
			cOption: [],
			popupType: 'warn'
		}
	},
	created() {
		this.combineRows()
	},
	methods: {
		// 风险预警查询
		getForecast(params) {
			this.pageLoading = this.$loading({
				lock: true,
				text: 'Loading',
				spinner: 'el-icon-loading',
				background: 'rgba(0, 0, 0, 0.7)'
			});
			Object.assign(this.product, params);
			params.startDate = params.date;
			getAction(this.urls.getRiskWarning, params).then(res => {
				if (res.msg === '成功' && res.objects) {
					this.cuitemap.addFeatureLayer('warn', res['objects']);
					this.pageLoading.close();
					(res.objects.length) || this.$message({
						message: '查询成功，但无数据',
						type: 'info',
					})
				}
			}).catch(err => {
				this.pageLoading.close()
			});
		},
		// 站点搜索
		searchSite(site) {
			console.log('站点搜索', site);
			if (site && site['longitude'] && site['latitude']) {
				site['lon'] = site['longitude'];
				site['lat'] = site['latitude'];
				this.cuitemap.addFeatureLayer('search', [site], true);
				this.cuitemap.fitToPoint(parseFloat(site['longitude']), parseFloat(site['latitude']))
			}
		},
		// 制作产品
		makeProduct(obj) {
			this.getMaker();
			this.dialogVisible = true;
			Object.assign(this.product, obj);
			// this.product.department = '梧州市气象局';
		},
		// 获取制作人
		getMaker() {
			getAction(this.urls.maker).then(res => {
				this.maker = { fUsers: [], eUsers: [], vUsers: [], };
				if (res.object && res.object.length) {
					const first = res.object[0]
					this.product.forecastUsr = first.forecastUsr;
					this.product.enteringUsr = first.enteringUsr;
					this.product.verifyUsr = first.verifyUsr;
					res.object.map((item) => {
						this.maker.fUsers.push({ label: item.forecastUsr, value: item.id })
						this.maker.eUsers.push({ label: item.enteringUsr, value: item.id })
						this.maker.vUsers.push({ label: item.verifyUsr, value: item.id })
					})
				}
			})
		},
		// 设置下拉列表
		makerFilter(queryString, cb, type) {
			let makers = this.maker[type];

			let results = queryString ? makers.filter(this.inputMakerFilter(queryString)) : makers;
			cb(results);
		},
		// 根据输入值筛选下拉列表
		inputMakerFilter(queryString) {
			return (item) => {
				return (item.label.toLowerCase().indexOf(queryString.toLowerCase()) !== -1);
			};
		},
		// 关闭弹窗
		handleClose() {
			this.dialogVisible = false;
			this.$refs.productForm.resetFields();
		},
		// 提交产品制作
		async submitProduct() {
			this.pageLoading = this.$loading({
				lock: true,
				text: 'Loading',
				spinner: 'el-icon-loading',
				background: 'rgba(0, 0, 0, 0.7)'
			});
			this.cuitemap.exportMap((base64) => {
				// console.log(base64)
			});
			let validate = false;
			this.$refs.productForm.validate((valid) => {
				validate = valid;
			})
			if (validate) {
				await postAction(this.urls.makeProduce, this.product).then(res => {
					console.log(res);
					if (res.msg === '成功') {
						this.$alert(`${res.object} 制作成功`, res.msg, {
							confirmButtonText: '确定',
							callback: action => {
								this.handleClose();
							}
						});
					}
				}).catch(err => {
					this.pageLoading.close();
				})
			}
			this.pageLoading.close();
		},
		getKey(key, active) {
			// 切换地图
			if (key === 'switch') this.changeMap(active)
		},
		// 获取map对象,初始化自定义map属性事件
		getMap(map) {
			// 获取view并fit
			this.cuitemap = new CuiteMap(map);
			this.cuitemap.addOverLayer();
			this.cuitefilter = new cuiteFilter(map);

			this.cuitemap.initBaseLayer(BaseMapConfig);

			this.cuitemap.initLayer('border', {
				fill_color: 'rgba(62,138,234,0.2)',
				stroke_color: 'rgba(62,138,234,1)',
				stroke_width: 2,
			});
			this.cuitemap.addGeoJSONLayer('border', cnBorder);

			this.cuitemap.initLayer('warn', {
				image_url: require('../../assets/images/circle.png'),
				image_scale: 1
			}, (data) => {
				this.popupType = 'warn'
				this.cOption = [data];
			});

			this.cuitemap.initLayer('search', {
				image_url: require('../../assets/images/location.png'),
				image_scale: 0.5
			}, (data) => {
				this.popupType = 'search'
				this.cOption = [data];
			});
		},
		refreshMap(data) {
			this.getForecast(this.product);
		},
		combineRows() {
			MapToolConfig.content.forEach((content) => {
				const temp = []
				temp.push(...content.row)
				temp.forEach((item) => {
					this.mapToolsRows.push({
						key: item.key,
						render: item.render,
						zIndex: item.zIndex,
						active: false
					})
				})
			})
		},

		// 切换地图
		changeMap(active) {
			this.cuitemap.changeBaseLayer(active);
		},
		clickHandler(key, active) {
			switch (key) {
				case 'ranging':
					this.measureLine()
					break
				case 'surface':
					this.measurePolygon()
					break
				case 'clear':
					clear(this.cuitemap.map, 'lineAndArea', 'measureOverlay')
					break
				case 'download':
					print(this.cuitemap.map)
					break
				case 'rectangle':
					this.geomFilter('RectAngle');
					break
				case 'circle':
					this.geomFilter('Circle');
					break
				case 'polygon':
					this.geomFilter('Polygon');
					break
				case 'clean':
					this.geomFilter();
					break
			}
		},
		geomFilter(type) {
			if (!type) {
				this.cuitefilter.clearFilter();
				return;
			}
			this.cuitefilter.activateFilter(this.cuitemap.getLayer('warn'), type, (result, extent) => {

				setTimeout(() => {
					this.cuitemap.setOverlayerCoordinate([extent[0], (extent[1] + extent[3]) / 2]);
					this.cOption = result;
				}, 30)
			}, (error) => {
				this.$message({
					message: '范围不能超过100平方公里！',
					type: 'warning'
				})
				return;
			});
		},
		measureLine() {
			measure(this.cuitemap.map, 'LineString')
		},
		measurePolygon() {
			measure(this.cuitemap.map, 'Polygon')
		}
	},
}
</script>

<style>
.w-40 {
	width: 10em;
}

.leading-10 {
	line-height: 2.5em;
}

.text-base {
	font-size: 1em;
}

.px-8 {
	padding-left: 2em;
	padding-right: 2em;
}

.leading-10 {
	line-height: 2.5em;
}

.text-sm {
	font-size: 0.875em;
}

.w-4 {
	width: 1em;
}

.h-4 {
	height: 1em;
}
</style>
<style lang="scss">
.fxyj-wrapper {
	.el-autocomplete {
		width: 100%;
	}
}

#map {
	position: absolute;
	top: 0;
	width: 100%;
	height: 100%;
	overflow: hidden;
}

.rowTool {
	height: 2em;
	line-height: 2em;
	width: 7em;
	text-align: left;
	cursor: pointer;
	.pic {
		margin-left: 1em;
		width: 1em;
		height: 1em;
		vertical-align: middle;
	}
	.spanText {
		vertical-align: middle;
		padding-left: 1em;
	}
	&:hover {
		background-color: #e0e0e0;
	}
}
</style>
